/**
 * Created by yujianfu on 2016/11/10.
 */
import React, {Component, PropTypes} from 'react'
import {Tabs, Card, Table, message, Button, Popover, Input, Popconfirm, Icon, Collapse} from 'antd'
import Styles from './../Index.less'
import {fetchPost} from './../../../../../utils/request'
const Panel = Collapse.Panel;

class CallAndSMS extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userId: props.userId,
      contactNum: 0,
      relationsNum: 0,
      exceptionNum: 0,
      list: [
        // {name: 'name0', inputName: 'inputName0', relation: "relation0", phone: 'mobile通讯录', }
      ],
      calls: [],
      contactSelfItem: null,
      callSelfItem: null,
      loading: false,
      sendList: [],
      content: '',
      selectedRowKeys: [],
      selectRows: [],
      display: false,
      showCalls: props.showCalls,
      item: props.item,
      collectionType: props.collectionType,

      contactVisible: false,
      callVisible: false,
      message: '',
      timer: null,
      id: props.id,
      total: 0,
      mechanism: 0,
      abnormal: 0,
      smsTotal: 0,
      smsMechanism: 0,
      smsRelative: 0,
      smslist: []
    }
  }

  componentWillUnmount () {
    clearTimeout(this.state.timer)
  }

  showBook() {
    this.setState({
      display: true,
    })
  };

  componentWillReceiveProps(props) {
    if (this.state.userId != props.userId) {
      let showCalls = true
      if (typeof (props.showCalls) !== 'undefined') {
        showCalls = false
      }

      this.setState({
        display: false,
        outerOverdue: props.outerOverdue,
        showCalls,
        userId: props.userId,
        item: props.item,

        id: props.id
      }, () => {
        this.getData(props.userId)
      })
    }
  }

  componentDidMount() {
    this.getData(this.state.userId)
  }

  getData(userId) {
    this.setState({
      loading: true
    });
    if (this.state.userId != null) {
      fetchPost(`/user/${this.state.userId}/contactCall/info`, {}).then(json => {
        if (json.code === 0) {
          if (json.data != null) {
            // console.log('returnMsg is ')
            // console.log(json.data.phoneCallRecordVO)

            this.setState({
              contactNum: json.data.contactNum || 0,
              relationsNum: json.data.relationsNum || 0,
              exceptionNum: json.data.exceptionNum || 0,
              list: json.data.list || [],
              calls: json.data.phoneCallRecordVO.phoneCallRecordItemVOList || [],
              total: json.data.phoneCallRecordVO.total || 0,
              mechanism: json.data.phoneCallRecordVO.mechanism || 0,
              abnormal: json.data.phoneCallRecordVO.abnormal || 0,
              contactSelfItem: json.data.contactSelfItem,
              callSelfItem: json.data.callSelfItem,
              loading: false,
              //smsTotal: json.data.smsRecordVO.total || 0,
              //smsMechanism: json.data.smsRecordVO.mechanism || 0,
              //smsRelative: json.data.smsRecordVO.relative || 0,
              //smslist: json.data.smsRecordVO.smsRecordItemVOList || []
            })
          }
        } else {
          this.setState({
            contactNum: '',
            relationsNum: '',
            exceptionNum: '',
            list: [],
            calls: [],
            loading: false,
            contactSelfItem: {},
            callSelfItem: {},
            message: json.msg
          })
        }
      })
    } else {
      this.setState({
        contactNum: '',
        relationsNum: '',
        exceptionNum: '',
        list: [],
        calls: [],
        loading: false,
        contactSelfItem: {},
        callSelfItem: {}
      })
    }
  }

  showCallTotal () {
    return (
      <div style={{display: 'inline-block'}}>
        Call Records &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        Total:{this.state.total}&nbsp;&nbsp;
        <span style={{color: "#8A2BE2"}}>Company:{this.state.mechanism}&nbsp;&nbsp;</span>
        <span style={{color: "#EE2C2C"}}>Abnormal:{this.state.abnormal}&nbsp;&nbsp;</span>
      </div>
    )
  }

  showSMSTotal () {
    return (
      <div style={{display: 'inline-block'}}>
        SMS Log &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span>Total:{this.state.total}&nbsp;&nbsp;</span>
        <span style={{color: "#6B8E23"}}>Relatives:{this.state.mechanism}&nbsp;&nbsp;</span>
        <span style={{color: "#EE2C2C"}}>Mechanism:{this.state.abnormal}&nbsp;&nbsp;</span>
      </div>
    )
  }

  showCallList () {
    this.setState({
      callVisible: true
    })
  }

  send(type, name, mobile, content) {
    if (this.state.userId != null) {
      fetchPost('/collection/v2/comment/add', {
        userCode: this.state.userId,
        tradeNo: this.state.item.tradeNo,
        collectionNo: this.state.item.collectionNo,
        followId: this.state.item.followId,
        followUp: this.state.item.followUp,
        name,
        relation: 'Call Records contacts',
        mobile,
        content,
        type,
      }).then(json => {
        if (json.code === 0) {
          message.info('Add success')
          this.props.recordRefresh()
        } else {
          message.error(json.msg)
        }
      })
    }
  }

  // 表单提交
  showContent(type, name, mobile, content) {
    if (content == null || content == '') {
      message.error('Please enter the content')
      return
    }
    if (content.replace(/\s+/g, '').length == 0) {
      message.error('Content can not be empty')
      return
    }
    this.send(type, name, mobile, content)
  }

  showSend(type, name, mobile) {
    let content = ''
    return (
      <div style={{width: 300}}>
        <Input className="mb10" addonBefore='Name：' defaultValue={name}
               onBlur={(e) => {
                 name = e.target.value
               }}/>
        <Input className="mb10" addonBefore='Mobile：' defaultValue={mobile}
               onBlur={(e) => {
                 mobile = e.target.value
               }}/>
        <Input className="mb10" addonBefore='Content：' type='textarea'
               placeholder='Please enter the content'
               onBlur={(e) => {
                 content = e.target.value
               }}
               autosize={{minRows: 4, maxRows: 6}}/>
        <div className="mt10" style={{overflow: 'hidden'}}>
          <Button style={{float: 'right'}} type='primary' size='small'
                  onClick={(e) => this.showContent(type, name, mobile,
                    content)}>New record</Button>
        </div>
      </div>
    )
  }

  isShow(record) {
    let mobile = record.phone
    if (mobile.indexOf('-') != -1 || mobile.indexOf('(') != -1 ||
      mobile.length != 11) {
      return true
    }
    return false
  }

  render() {
    const callsColumns = [
      {
        title: 'Last Contact Time',
        dataIndex: 'lastTimeStr',
        key: 'lastTimeStr'
      },
      {
        title: 'Mobile',
        dataIndex: 'phone',
        key: 'phone'
      },
      {
        title: 'Caller',
        dataIndex: 'mechanism',
        key: 'mechanism'
      },
      {
        title: 'Location',
        dataIndex: 'attribution',
        key: 'attribution'
      },
      {
        title: 'Call Out/Call In',
        dataIndex: 'callInAndOut',
        key: 'callInAndOut'
      },
      {
        title: 'Call Duration（s)',
        dataIndex: 'totalCallDuration',
        key: 'totalCallDuration'
      },
      {
        title: 'Phone Record',
        render: (record) => {
          return <Popover key={Math.random().toString(16).substring(2)}
                          content={this.showSend(2, record.name,
                            record.phone)}
                          title='Phone Record'
                          trigger='click'
          >
            <Button type='primary' size='small'>Record</Button>
          </Popover>
        },
      }
    ];

    const smsColumns = [
      {
        title: 'Last Time',
        dataIndex: 'lastTime',
        key: 'lastTime'
      },
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: 'Mobile',
        dataIndex: 'mobile',
        key: 'mobile'
      },
      {
        title: 'Number Of Messages',
        dataIndex: 'messageNum',
        key: 'messageNum'
      },
      {
        title: 'Content',
        dataIndex: 'content',
        key: 'content'
      },
      {
        title: 'SMS Record',
        render: (record) => {
          return <Popover key={Math.random().toString(16).substring(2)}
                          content={this.showSend(1, record.name,
                            record.phone)}
                          title='SMS content'
                          trigger='click'
          >
            <Button type='primary' size='small'>Record</Button>
          </Popover>
        }
      },
    ];

    return (
      <div className={Styles.detailModule}>
        <Collapse defaultActiveKey={['2', '3']}>

          <Panel header={this.showCallTotal()} key="2">
            <div style={{maxHeight: 300, overflow: 'auto', textAlign: 'center'}}>
              {
                this.state.calls.length < 100 || this.state.callVisible
                  ? <Table
                    size='small'
                    pagination={false}
                    bordered
                    dataSource={this.state.calls}
                    columns={callsColumns}
                    key='name2'
                    loading={this.state.loading}
                  />
                  : <Button type='primary' className='mt10 mb10' onClick={() => {
                    this.showCallList()
                  }}>Show</Button>
              }
            </div>
          </Panel>

          <Panel header={this.showSMSTotal()} key="3">
            <div style={{maxHeight: 300, overflow: 'auto', textAlign: 'center'}}>
              {
                this.state.calls.length < 100 || this.state.callVisible
                  ? <Table
                    size='small'
                    pagination={false}
                    bordered
                    dataSource={this.state.smslist}
                    columns={smsColumns}
                    key='name3'
                  />
                  : <Button type='primary' className='mt10 mb10' onClick={() => {
                    this.showCallList()
                  }}>Show</Button>
              }

            </div>

          </Panel>
        </Collapse>

      </div>
    )
  }
}

export default CallAndSMS
